# Maintainer: Alexey Kasatkin <alexeikasatkin@gmail.com>

_realname=libosmpbf
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
conflicts=("${MINGW_PACKAGE_PREFIX}-${_realname}-git")
replaces=("${MINGW_PACKAGE_PREFIX}-${_realname}-git")
pkgver=1.5.0
pkgrel=3
pkgdesc="A library to support OpenStreetMap's protocolbuffer binary .pbf format (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clangarm64' 'clang32')
url="https://github.com/openstreetmap/OSM-binary"
license=('spdx:LGPL-3.0-only')
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
depends=("${MINGW_PACKAGE_PREFIX}-protobuf"
         "${MINGW_PACKAGE_PREFIX}-zlib")
source=("${_realname}-${pkgver}.tar.gz::https://github.com/openstreetmap/OSM-binary/archive/v${pkgver}.tar.gz"
        001-fix-linking.patch
        002-Do-not-set-CXX-version-any-more.patch::https://github.com/openstreetmap/OSM-binary/commit/6e9c0076.patch)
sha256sums=('2abf3126729793732c3380763999cc365e51bffda369a008213879a3cd90476c'
            'f175ae52f195a93da90cde5c4b249d0b3c7d3fbb95bddbc2ea0aafd3677aafe6'
            'd4c2b82c37e354fad81f3484352d6d3f7380a5c46c4119f7a441114544201804')
noextract=(${_realname}-${pkgver}.tar.gz)

prepare() {
  plain "Extracting ${_realname}-${pkgver}.tar.gz due to symlink(s) without pre-existing target(s)"
  [[ -d ${srcdir}/OSM-binary-${pkgver} ]] && rm -rf ${srcdir}/OSM-binary-${pkgver}
  tar -xzvf ${srcdir}/${_realname}-${pkgver}.tar.gz -C ${srcdir} || true

  cd ${srcdir}/OSM-binary-${pkgver}
  patch -p1 -i ${srcdir}/001-fix-linking.patch
  patch -p1 -i ${srcdir}/002-Do-not-set-CXX-version-any-more.patch

  cp -rf ${srcdir}/OSM-binary-${pkgver}/{src,osmpbf}
}

build() {
  mkdir -p "${srcdir}/build-${MSYSTEM}" && cd "${srcdir}/build-${MSYSTEM}"

  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  CXXFLAGS+=" -DPROTOBUF_USE_DLLS" \
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    "${_extra_config[@]}" \
    -DCMAKE_CXX_STANDARD=17 \
    ../OSM-binary-${pkgver}

  ${MINGW_PREFIX}/bin/cmake --build .
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"
  DESTDIR=${pkgdir} ${MINGW_PREFIX}/bin/cmake --install .
  install -Dm644 ${srcdir}/OSM-binary-${pkgver}/LICENSE ${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE
}
